﻿using CQRSFramework.Common.Serializer;
using CQRSFramework.Infrustructures;
using System.Collections.Generic;

namespace CQRSFramework.Events.Impl
{
    public class EventJsonSerializer : IEventJsonSerializer
    {
        private readonly ITypeNameProvider _typeNameProvider;
        private readonly IJsonSerializer _jsonSerializer;
        public EventJsonSerializer(ITypeNameProvider typeNameProvider, IJsonSerializer jsonSerializer)
        {
            _typeNameProvider = typeNameProvider;
            _jsonSerializer = jsonSerializer;
        }

        public IEnumerable<IDomainEvent> Deserialize(IDictionary<string, string> events)
        {
            List<IDomainEvent> domainEvents = new List<IDomainEvent>();
            foreach (var evnt in events)
            {
                var type = _typeNameProvider.Get(evnt.Key);
                domainEvents.Add(_jsonSerializer.Deserialize<IDomainEvent>(evnt.Value, type));
            }
            return domainEvents;
        }

        public IDictionary<string, string> Serialize(IEnumerable<IDomainEvent> domainEvents)
        {
            IDictionary<string, string> dictionary = new Dictionary<string, string>();
            foreach (var domainEvent in domainEvents)
            {
                dictionary.Add(_typeNameProvider.GetTypeName(domainEvent.GetType()), _jsonSerializer.Serialize(domainEvent));
            }
            return dictionary;
        }
    }
}
